package com.cloudlead.common.worker.web;

import com.cloudlead.common.worker.ApiRegistry;
import com.sun.enterprise.mgmt.transport.NetworkUtility;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;

/**
 * Created by dean on 2015/7/29.
 */
public class WorkerServer extends SimpleServer {
    protected String workerName;

    public WorkerServer(String workerName) {
        this(workerName, null, DEFAULT_SERVER_PORT, DEFAULT_CONTEXT_PATH, DEFAULT_SPRING_ROOT);
    }

    public WorkerServer(String workerName, String serverHost, int serverPort) {
        this(workerName, serverHost, serverPort, DEFAULT_CONTEXT_PATH, DEFAULT_SPRING_ROOT);
    }

    public WorkerServer(String workerName, String serverHost, int serverPort, String contextPath) {
        this(workerName, serverHost, serverPort, contextPath, DEFAULT_SPRING_ROOT);
    }

    public WorkerServer(String workerName, String serverHost, int serverPort, String contextPath, Class<?> springRootConfiguration) {
        super(serverHost, serverPort, contextPath, springRootConfiguration);
        this.workerName = workerName;
    }

    @Override
    public void start() throws Exception {
        super.start();

        WorkerInfo workerInfo = new WorkerInfo(serverHost, serverPort);
        if (StringUtils.isBlank(serverHost) || NetworkUtility.getAnyAddress().getHostAddress().equals(serverHost)) {
            try {
                String hostAddress = NetworkUtility.getFirstInetAddress().getHostAddress();
                workerInfo.setWorkerIp(hostAddress);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        workerInfo.setWorkerName(workerName);

        WorkerManager.getInstance().joinGroup(workerInfo, springContext.getBean(ApiRegistry.class),false);

    }

    @Override
    public void stop() throws Exception {
        super.stop();
        WorkerManager.getInstance().leaveGroupAndShutdown();
    }
}
